/*
 ============================================================================
 Name		: AudioPlayer.cpp
 Author	  : Lenka Litvova
 Version	 : 1.0
 Copyright   : Copyright belongs to Lenka Litvova
 Description : CAudioPlayer implementation
 ============================================================================
 */

#include "AudioPlayer.h"

CAudioPlayer::CAudioPlayer()
	{
	// No implementation required
	}

CAudioPlayer::~CAudioPlayer()
	{
		if(iPlayer)
		{
			if(iPlaying)
				iPlayer->Stop();
			iPlayer->Close();
		}
		
	    delete iPlayer;

	}

CAudioPlayer* CAudioPlayer::NewLC()
	{
	CAudioPlayer* self = new (ELeave) CAudioPlayer();
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}

CAudioPlayer* CAudioPlayer::NewL()
	{
	CAudioPlayer* self = CAudioPlayer::NewLC();
	CleanupStack::Pop(); // self;
	return self;
	}

void CAudioPlayer::ConstructL()
	{
		//iPlayer = CMdaAudioPlayerUtility::NewFilePlayerL(aFileName, *this);
		iPlaying = EFalse;
		iPrepared = EFalse;
	}

//From MMdaAudioToneObserver
void CAudioPlayer::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& aDuration)
	{
		if(aError == KErrNone)
		{
			iPrepared = ETrue;
			iPlayer->SetVolume(iPlayer->MaxVolume());
			iPlayer->Play();
			iPlaying = ETrue;
		}
	}

//From MMdaAudioToneObserver
void CAudioPlayer::MapcPlayComplete(TInt aError)
	{
		iPlaying = EFalse;
	}

void CAudioPlayer::PlayFile(const TDesC &aFileName)
	{
		iPlayer = CMdaAudioPlayerUtility::NewFilePlayerL(aFileName, *this);
	}

void CAudioPlayer::PlayText(const TDesC &aText)
	{
		_LIT( KTtsPrefix, "(tts)" );

		HBufC8* playableText = HBufC8::NewLC( aText.Length() + KTtsPrefix().Length() );
		 
		playableText->Des().Append( KTtsPrefix );
		playableText->Des().Append( aText );
		
		iPrepared = EFalse;
		iPlaying = EFalse;
		if(iPlayer)
		{
			if(iPlaying)
				iPlayer->Stop();
			iPlayer->Close();
		}
				
		delete iPlayer;
		
		iPlayer = CMdaAudioPlayerUtility::NewL(*this);
		iPlayer->OpenDesL( *playableText );
	}

void CAudioPlayer::Stop()
	{
		iPlayer->Stop();
		iPlaying = EFalse;
	}

void CAudioPlayer::Replay()
	{
		if(iPrepared)
		{
			iPlayer->Play();
			iPlaying = ETrue;
		}
	}
